package com.mbc.common.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import com.mbc.common.dao.DAO;
import com.mbc.common.entities.Log;

public class LogDAOImpls extends DAO<Log> implements LogDAO {
	
	public LogDAOImpls(Connection conn) {
		this.conn = conn;
	}

	@Override
	public void getData(Log logentity) throws SQLException {
		String runquery = "INSERT INTO " + logentity.getTablename() + "_Log SELECT '" + logentity.getLogkey() + "', ";
		query = "SELECT * FROM " + logentity.getTablename() + " WHERE " + getPColumn(logentity) + " = " + logentity.getKey();
		pstmt = conn.prepareStatement(query);
		rs = pstmt.executeQuery();
		ResultSetMetaData rsmd = rs.getMetaData();
		if(rs.next()) {
			int columnsNumber = rsmd.getColumnCount();
			for(int i = 0; i < columnsNumber; i++) {
				if(rs.getString(i + 1) != null)
					runquery += "N'" + rs.getString(i + 1) + "',";
				else
					runquery += "NULL,";
			}
		}
		
		rs.close();
		pstmt.close();
		
		runquery += "GETDATE(), " + logentity.getUserid() + ", " + logentity.getLogstatus();
		saveLog(runquery);
	}
	
	public void saveLog(String query) throws SQLException {
		pstmt = conn.prepareStatement(query);
		pstmt.execute();
		pstmt.close();
	}

	@Override
	protected Log readRecord(ResultSet rs) throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getPColumn(Log logentity) throws SQLException {
		String l_result = "";
		query = "SELECT column_name " +
				"FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE " +
				"WHERE OBJECTPROPERTY(OBJECT_ID(constraint_name), 'IsPrimaryKey') = 1 " +
				"AND table_name = '" + logentity.getTablename() + "'";
		pstmt = conn.prepareStatement(query);
		rs = pstmt.executeQuery();
		if (rs.next())
			l_result = rs.getString("column_name");
		rs.close();
		pstmt.close();
		
		return l_result;
	}
	
}
